<?php
class Page_management extends MY_Controller{
	
 	function __construct()
    {
    	parent::__construct();
    }
	function _remap($method,$params = array())
	{
	   $this->_admin_remap($method,$params);	   
	}
	function index() {
		$this->load->model('Language');
		foreach($this->Language->get_all() as $row){
			$data['langList'][$row['language_code']] = $row['language_name'];
		}
    	$this->_setLayout('admin/page_management','admin_layout',$data);
    }
	function add_page(){
    	$callback = $_REQUEST['callback'];
    	$jsonOutPut = '';
		try{
	    	$data = json_decode ($_GET['data'],true);
	    	if(empty($data)){
	    		$jsonOutPut = json_encode(array('success'=>false,'message'=>'Can not save'));	    			    		
	    	}
	    	else{
		    	$this->load->model('Page');
		    	if(isset($data['id'])){
		    		$this->Page->update($data,$data['id']);
		    		$data_return = $this->Page->get_by_id($data['id']);
		    		$data_return['edit'] = '<a href="'.base_url().'admin/page_management/edit_page/'.$data['id'].'"><img src="'.base_url().'public/skin/back-end/images/edit.png"></a>';
		    		$jsonOutPut = json_encode(array('success'=>true,'message'=>'Saved successfully','data'=>$data_return));
		    	}	
		    	else{	
		    		$id = $this->Page->insert($data);
		    		$data_return = $this->Page->get_by_id($id);
		    		$data_return['edit'] = '<a href="'.base_url().'admin/page_management/edit_page/'.$id.'"><img src="'.base_url().'public/skin/back-end/images/edit.png"></a>';
		    		$jsonOutPut = json_encode(array('success'=>true,'message'=>'Loaded data','data'=>$data_return));
		    	}		 
	    	}
	    	   	
    	}
    	catch (Exception $e){
    		$jsonOutPut = json_encode(array('success'=>false,'message'=>'Can not save'));
    	}
    	if ($callback) {
		    header('Content-Type: text/javascript');
		    echo $callback . '(' . $jsonOutPut . ');';
		} else {
		    header('Content-Type: application/x-json');
		    echo $jsonOutPut;
		}	
    }
	function delete_page(){
		$callback = $_REQUEST['callback'];
		$jsonOutPut = '';
		try{
			$data = json_decode ($_GET['data'],true);			
    		$this->load->model('Page');
    		$this->Page->delete($data);
			$jsonOutPut =  json_encode(array('success'=>true));
		}
    	catch (Exception $e){
    		$jsonOutPut =  json_encode(array('success'=>false));
    	}
    	if ($callback) {
		    header('Content-Type: text/javascript');
		    echo $callback . '(' . $jsonOutPut . ');';
		} else {
		    header('Content-Type: application/x-json');
		    echo $jsonOutPut;
		}	
    }
    function page_grid(){
    	$this->load->model('Page');
	    $callback = $_REQUEST['callback'];
	    $data =  array();
	    foreach($this->Page->get_list($_GET['start'],$_GET['limit'],(isset($_GET['sort']))?$_GET['sort']:'id',(isset($_GET['dir']))?$_GET['dir']:'DESC') as $row){
	    	$data[] = array_merge($row,array('edit'=>'<a href="'.base_url().'admin/page_management/edit_page/'.$row['id'].'"><img src="'.base_url().'public/skin/back-end/images/edit.png"></a>'));
	    }
		$jsonOutPut = json_encode(array('success'=>true,'message'=>'Loaded data','start'=>$_GET['start'],'total'=>$this->Page->get_total(),'data'=>$data));
		if ($callback) {
		    header('Content-Type: text/javascript');
		    echo $callback . '(' . $jsonOutPut . ');';
		} else {
		    header('Content-Type: application/x-json');
		    echo $jsonOutPut;
		}
    }
	function edit_page($page_id=null){
		if(empty($page_id))
			header('Location: '.base_url().'admin/page_management/');
		else {		
			$this->load->model('Page');
			$this->load->model('Language');
			
			$message = null;
			if($this->input->server('REQUEST_METHOD') == 'POST'){
				if($this->Page->update($_POST,$page_id))
					$message = 'Update content successfully';
				else	
					$message = 'Update content fail';
			}
			$data = array('page' => $this->Page->get_by_id($page_id),
						  'message'=>$message);
			/*---Get elements from template---*/
			if(!empty($data['page']['template'])&&file_exists(getcwd().'/application/views/front/'.$data['page']['template'].'.php')){
	        	$data['page']['elements'] = $this->_read_template($data['page'],$data['page']['template']);
			}
			/*--------------------------------*/
			foreach($this->Language->get_all() as $row){
				$data['langList'][$row['language_code']] = $row['language_name']; 
			}			
			$this->_setLayout('admin/edit_page', 'admin_layout', $data);
		}	
	}
	function add_elements(){
		if($this->input->server('REQUEST_METHOD') == 'POST'){
			$template = $this->input->post('template');
			$page_id = $this->input->post('page_id');
			$this->load->model('Page');
			$current_page = $this->Page->get_by_id($page_id);
			if(file_exists(getcwd().'/application/views/front/'.$template.'.php')){				
	        	$elements_list = $this->_read_template($current_page,$template);
	        	foreach($elements_list as $row){
	        		echo $row;
	        	}
			}
		}	
	}
	function _read_template($current_page,$template){
			$filecontent = file_get_contents(getcwd().'/application/views/front/'.$template.'.php');
			$pattern = "/front_element\(['\"](?P<type>\w*)['\"]\s*\,\s*['\"](?P<name>\w*)['\"]/";
			preg_match_all($pattern, $filecontent, $elements_tpl);
			$current_page['elements'] = (!empty($current_page['elements']))?unserialize($current_page['elements']):array();
        	$tmp_page_elements = array();
        	if(isset($elements_tpl)&&!empty($elements_tpl)){
	        	for($i=0;$i<count($elements_tpl['type']);$i++){
	        		$value = (isset($current_page['elements'][$elements_tpl['type'][$i]][$elements_tpl['name'][$i]]))?$current_page['elements'][$elements_tpl['type'][$i]][$elements_tpl['name'][$i]]:null;
	        		$tmp_page_elements[$elements_tpl['name'][$i]] = $elements_tpl['type'][$i]("elements[{$elements_tpl['type'][$i]}][{$elements_tpl['name'][$i]}]",ucwords(str_replace('_', ' ', $elements_tpl['name'][$i])),$value);
				}
        	}
        	return $tmp_page_elements;
	}
}